/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
 */

package controllers

import (
	"encoding/json"
	"prim-server/common"
	"prim-server/errcode"
	"prim-server/logger"
	"prim-server/primservice/validator"
	billService "prim-server/service/bill"
	userService "prim-server/service/user"

	"github.com/pkg/errors"
)

const (
	QueryCommonUserBillURL = "/v1/user/bill/query"

	QueryAllUserBillURL = "/v1/partner/bill/query"
)

type BillController struct {
	CommonController
}

func (bc *BillController) QueryCommonUserBill() {
	req := common.QueryBillCommonRequest{}
	if err := json.Unmarshal(bc.Ctx.Input.RequestBody, &req); err != nil {
		bc.HandleErrCode(errcode.E.Base.RequestInvalid.WithErr(err))
		return
	}
	if err := validator.Validate(&req); err != nil {
		bc.HandleErrCode(errcode.E.Base.RequestInvalid.WithErr(err))
		return
	}
	//校验是否为当前登录用户
	if err := bc.CheckUserIdFromSession(req.UserId); err != nil {
		err := errors.New("check user error")
		logger.Error(err.Error())
		bc.HandleErrCode(errcode.E.Base.ErrorMessage.WithMessage("用户检验失败"))
		return
	}
	response, err := billService.BuildResponseForQueryBillCommonUser(&req)
	if err != nil {
		bc.HandleErrCode(errcode.E.Internal.Internal.WithErr(err))
		return
	}
	bc.HandleBusinessObj(response)
}

func (bc *BillController) QueryAllUserBill() {
	req := common.QueryBillRequestForAdmin{}
	if err := json.Unmarshal(bc.Ctx.Input.RequestBody, &req); err != nil {
		bc.HandleErrCode(errcode.E.Base.RequestInvalid.WithErr(err))
		return
	}
	if err := validator.Validate(&req); err != nil {
		bc.HandleErrCode(errcode.E.Base.RequestInvalid.WithErr(err))
		return
	}
	//校验是否为当前登录用户
	if err := bc.CheckUserIdFromSession(req.UserId); err != nil {
		err := errors.New("check user error")
		logger.Error(err.Error())
		bc.HandleErrCode(errcode.E.Base.ErrorMessage.WithMessage("用户检验失败"))
		return
	}
	admin, err := userService.GetAdminId()
	if err != nil || admin != req.UserId {
		err := errors.New("get admin error, check user error")
		logger.Error(err.Error())
		bc.HandleErrCode(errcode.E.Base.ErrorMessage.WithMessage("用户检验失败"))
		return
	}
	response, err := billService.BuildResponseForQueryBillAdminUser(&req)
	if err != nil {
		bc.HandleErrCode(errcode.E.Internal.Internal.WithErr(err))
		return
	}
	bc.HandleBusinessObj(response)
}
